import { onMounted, reactive, toRefs } from 'vue'
import { overallOptions } from '@/api/public.js'
import { strHump } from '@/utils/index'

const isString = val =>
  Object.prototype.toString.call(val) === '[object String]'

const isArray = val => Object.prototype.toString.call(val) === '[object Array]'

export function useFetchSelect(props) {
  const { params } = props

  const data = reactive({
    options: {},
    loading: false,
  })

  const loadData = () => {
    data.loading = true
    data.options = {}

    let _params = params
    if (isString(_params)) {
      _params = [_params]
    }

    return overallOptions({ params: _params }).then(
      res => {
        const { data: _data } = res
        data.loading = false
        let _obj = {}
        for (let item of _params) {
          const _result = _data[strHump(item)]
          const _item = isArray(_result) ? { [item]: _result } : _result
          _obj = Object.assign({}, _obj, _item || null)
        }
        data.options = _obj
        return _obj
      },
      err => {
        data.loading = false
        data.options = {}
        return Promise.reject(err)
      }
    )
  }

  onMounted(() => {
    loadData()
  })

  return toRefs(data)
}
